<template>
    <div class="page">
        <gzg-search :config="searchConfig" 
                    :form="searchForm"
                    :show-more="true"
                    :label-width="120"
                    @search="search"></gzg-search>
        <div class="tool-wrap">    
            <div class="item">
                <div class="label">赠送商家账号额度:</div>
                <div class="val">{{ stat_data.gift_num }}</div>
            </div> 
            <div class="item">
                <div class="label">已开通商户数:</div>
                <div class="val">{{ stat_data.open_seller_num }}</div>
            </div>  
            <div class="item link" @click="viewRegion">服务区域范围</div>

            <el-button class="btn" :icon="Plus" type="primary" @click="openDialog">新增</el-button>
        </div>
        <div class="grid-wrap">
            <el-table style="width:100%;"
                              height="100%"
                              :border="true"
                              :data="listData.data">
                <el-table-column label="序号" type="index" width="60px" fixed="left"></el-table-column>
                <el-table-column label="商家全称" prop="company_name" width="200px" fixed="left"></el-table-column>
                <el-table-column label="商家简称" prop="short_name" min-width="120px"></el-table-column>
                <el-table-column label="服务商" prop="agent_service_name" min-width="100px"></el-table-column>
                <el-table-column label="服务商分成比例" prop="agent_service_rate" min-width="130px">
                    <template #default="props">
                        <div>
                            <div v-for="(text, index) in props.row.service_rate_arr" :key="index">{{ text }}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="区域渠道" prop="agent_partner_name" min-width="100px"></el-table-column>
                <el-table-column label="渠道分成比例" prop="agent_partner_rate" min-width="120px">
                    <template #default="props">
                        <div>
                            <div v-for="(text, index) in props.row.partner_rate_arr" :key="index">{{ text }}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="状态" prop="seller_status_desc" width="80px"></el-table-column>
                <el-table-column label="接口参数" prop="create_user" width="100px">
                    <template #default="props">
                        <div>{{  props.row.is_set_api ? '已填写' : '未填写' }}</div>
                    </template>
                </el-table-column>

                <el-table-column label="创建人" prop="create_user" width="140px"></el-table-column>
                <!-- <el-table-column label="创建时间" prop="create_at" width="180px"></el-table-column> -->
                <el-table-column label="操作" width="196px" fixed="right">
                    <template #default="props">
                        <div>
                            <el-button type="primary" @click="view(props.row)" v-if="props.row.button.view_btn" link>详情</el-button>
                            <el-button type="primary" @click="viewQRcode(props.row)" v-if="props.row.button.qrcode_btn" link>二维码</el-button>
                            
                            <el-button type="primary" @click="edit(props.row)" v-if="props.row.button.edit_btn" link>重新提交</el-button>

                        </div>
                    </template>
                </el-table-column>

            </el-table>
        </div>
        <div class="page-wrap">
            <el-pagination
                v-model:current-page="params.page"
                v-model:page-size="params.page_size"
                :page-sizes="[100, 200, 300, 400]"
                layout="total, prev, pager, next"
                :total="listData.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        <add-form v-if="show" :drawer-show="show" :state="state" :id="id"  @refresh="refresh" @close="show = false"></add-form>       
        <el-dialog v-model="showQr" title="门店二维码" width="400px" append-to-body>
            <div style="text-align: center;">
                <div class="seller-qr-wrap" ref="img">
                    <img class="bg" src="../../../assets/common/qr-bg.png" alt="" style="width: 100%;">
                    <div id="qrcode" ref="qrcode"></div>
                    <div class="company-name">{{ companyName }}</div>
                </div>
                <el-button @click="downloadQRcode" type="primary" style="margin-top:10px">下载二维码</el-button>
            </div>
            
        </el-dialog>
        <el-dialog v-model="regionShow" title="服务区域范围" width="480px">
            <div>
                <div class="regin-item" style="margin-bottom: 12px;" v-for="(text,index) in agentRegionList" :key="index">{{ text }}</div>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed ,onMounted,getCurrentInstance,nextTick } from 'vue'
import { InfoFilled, Plus, Search, Hide, View, Close  } from '@element-plus/icons-vue'
import { ElMessageBox,ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

import QRCode from "qrcodejs2-fix"
import html2canvas from "html2canvas"

import addForm from './component/add-form'

import { assign } from 'lodash'

import { getBankShopList,getServiceArea } from 'services/shop'

import systemStore from '@/store/modules/system'

const show = ref(false)
const id = ref()
const state = ref('add')
const showQr = ref(false)

const regionShow = ref(false)

const searchForm = reactive({
    company_name:'',
    seller_status: '',
    partner_id:'',
    service_id:''
})

const stat_data = ref({
    gift_num:'0',
    open_seller_num:'0'
})

const searchConfig = reactive([{
    id:'company_name',
    label:'商户全称',
    placeholder:'请输入商户全称',
    type: 'input'
},{
    id:'short_name',
    label:'商户简称',
    placeholder:'请输入商户简称',
    type: 'input'
},{
    id:'seller_status',
    label:'状态',
    placeholder:'请选择状态',
    type: 'select',
    enum:'seller_status_list'
},])

const listData = reactive({
    total:0,
    data:<any>[]
})

const params = ref({
    company_name:'',
    seller_status:'',
    page_size:  20,
    page:  1,
})

const search = (searchParams:any) => {

    assign(params.value, searchParams)

    params.value.page = 1

    getList()
}

const handleSizeChange = (val: number) => {
    params.value.page_size = val
    params.value.page = 1
    getList();
}

const handleCurrentChange = (val:number) => {
    params.value.page = val
    getList()
} 

const refresh = () => {
    params.value.page = 1
    show.value = false
    getList()
}

const getList = () => {
    getBankShopList(params.value).then(res => {
        console.log(res)
        if (params.value.page == 1) {
            stat_data.value = res.stat_data || {
                gift_num:'0',
                open_seller_num:'0'
            }
        }
        listData.total = parseInt(res.total_rows)
        listData.data = res.items || []
    })
}

const openDialog = () => {
    show.value = true
    state.value = 'add'
    id.value =''
}

const closeDialog = () => {
    show.value = false
}

const view = (row:any) => {
    id.value = row.id
    show.value = true
    state.value = 'view'
}

const edit = (row:any) => {
    id.value = row.id
    show.value = true
    state.value = 'edit'
}


const { proxy } = getCurrentInstance()

var qrcodeInstance:any = null;

const companyName = ref('')

const viewQRcode = (row:any) => {
    showQr.value = true 
    
    nextTick(() => {
        companyName.value = row.short_name
        let h5_url = import.meta.env.GZG_H5_URL
        if (qrcodeInstance) {
            
            qrcodeInstance.clear()
            qrcodeInstance.makeCode(`${h5_url}/order/create?seller_id=${row.id}`); //生成另一个新的二维码

        } else {
            qrcodeInstance = new QRCode(proxy.$refs.qrcode, {
                text: `${h5_url}/order/create?seller_id=${row.id}`, // 二维码承载信息
                width: 150,
                height: 150,
                colorDark: '#000000',
                colorLight: '#ffffff', 
                correctLevel: QRCode.CorrectLevel.H  // 容错级别
            })
        }
        
    })
}

const downloadQRcode = () => {
    let options = {
        dpi: window.devicePixelRatio * 4,
        scale:4,
        useCORS:true,
        allowTaint:false,
        height:510,
        width: 360
    }

    html2canvas(proxy.$refs.img,options).then(canvas => {
        var url = canvas.toDataURL('image/png');
        let a = document.createElement("a");
        a.href = url;
        a.download = "qrcode";
        a.target = "_blank";
        a.click();
        a.remove();         
    });
}


const agentRegionList = ref<any[]>([])

const viewRegion = () => {
    getServiceArea().then(res => {
        regionShow.value = true
        agentRegionList.value = res.region_text_list
    })
}


const dict = computed(() => {
    console.log(dict)
    return systemStore().dict
})

onMounted(() => {
    getList()
})
</script>
<style lang="scss">
.seller-qr-wrap{
    width: 100%;
    position: relative;

    .bg{
        width: 100%;
        display: block;
    }

    #qrcode{
        width: 150px;
        height: 150px;
        position: absolute;
        left: 50%;
        top: 110px;
        transform: translateX(-50%);
    }

    .company-name{
        position: absolute;
        top:265px;
        left: 50%;
        transform: translateX(-50%);
        width: 150px;
        text-align: center;
        font-weight: 500;
        color: #333;
    }
}
</style>